import axios from 'axios'
import { useMain, store } from "../store/index";
import { getUserRefreshToken, deleteCookie } from "../utils/utils"
import router from "../routes/index"

const uploadFileAxios = axios.create();//新建一个axios实例
uploadFileAxios.defaults.timeout = 60000;
if (import.meta.env.VITE_ENV != 'production') {
    uploadFileAxios.defaults.baseURL = import.meta.env.VITE_BASE_API
} else {
    uploadFileAxios.defaults.baseURL = location.origin;
}
uploadFileAxios.defaults.headers['Content-Type'] = 'multipart/form-data';

let loading: any = null;

const useMainStore = useMain(store);
//请求拦截器
uploadFileAxios.interceptors.request.use((config) => {
    // console.log('config',config.url);

    // console.log('useMain',useMainStore.authToken);
    const token = useMainStore.authToken ? useMainStore.authToken : '';
    const currentProjectInfo: any = useMainStore.currentProjectInfo ? useMainStore.currentProjectInfo : {};
    if (token) {
        // 在发起请求前，给所有请求的头部添加token
        config.headers['Authorization'] = token;
    }
    if (currentProjectInfo && currentProjectInfo.projectId) {
        // 在发起请求前，给所有请求的头部添加token
        config.headers['Project-Id'] = currentProjectInfo.projectId;
    }
    //平台类型
    config.headers['Platform-Type'] = 3;
    //当请求刷新令牌接口时,请求头Authorization替换为之前的refreshToken
    if (config.url == '/user/auth/refreshToken' && useMainStore.refreshToken) {
        config.headers['Authorization'] = useMainStore.refreshToken;
    }
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        // background: 'rgba(0, 0, 0, 0.7)',
    })
    return config
}, (error) => {
    return Promise.reject(error)
})



//响应拦截器
uploadFileAxios.interceptors.response.use(response => {
    loading && loading.close();//关闭loading
    loading = null;//清空loading


    let res = response.data;
    if (!response.data) {
        res = response;
    }
    // console.log('response', response);
    // console.log('res',res);

    if (res && res.resultCode === '200' || res.resultCode === '201') {//请求成功时的处理
        return Promise.resolve(res);
    } else if (res && (res.resultCode === '403' || res.resultCode === '403-2' || res.resultCode === '403-3' || res.resultCode === '403-4' || res.resultCode === '403-5' || res.resultCode === '403-6')) {
        // window.location.href = "/login";
        //清空登录信息
        useMainStore.updatedAuthToken("");
        useMainStore.updatedRefreshToken("");
        useMainStore.updatedUserInfo({});
        deleteCookie("authToken");
        deleteCookie("refreshToken");
        router.push('/login');
    }
    else {//请求失败时的处理

        //发送验证码,手机号未登记时,不用统一报错方式
        if (response.config && response.config.url == '/msg/shortMsg/sendSmsCode' && res.resultMsg == '手机号未登记') {

        } else {
            ElMessage({
                message: res.resultMsg ? res.resultMsg : "连接超时,请稍后重试",
                grouping: true,
                type: 'error',
            })
        }
    }
    return Promise.reject(res)
}, async (error) => {
    loading && loading.close();//关闭loading
    loading = null;//清空loading
    if (error.response && error.response.data) {
        if (error.response.data.resultCode == '403-1') {
            await getUserRefreshToken();
            return uploadFileAxios(error.config)
        } else if (error.response.data.resultCode == '403' || error.response.data.resultCode == '403-2' || error.response.data.resultCode == '403-3' || error.response.data.resultCode == '403-4' || error.response.data.resultCode == '403-5' || error.response.data.resultCode == '403-6') {
            //清空登录信息
            useMainStore.updatedAuthToken("");
            useMainStore.updatedRefreshToken("");
            useMainStore.updatedUserInfo({});
            deleteCookie("authToken");
            deleteCookie("refreshToken");
            router.push('/login');
        } else {
            ElMessage({
                message: error.response.data.resultMsg ? error.response.data.resultMsg : "连接超时,请稍后重试",
                grouping: true,
                type: 'error',
            })
        }
    } else if (error.resultCode && error.resultMsg) {
        if (error.resultCode == '403-1') {
            await getUserRefreshToken();
            return uploadFileAxios(error.config)
        } else if (error.resultCode == '403' || error.resultCode == '403-2' || error.resultCode == '403-3' || error.resultCode == '403-4' || error.resultCode == '405' || error.resultCode == '406') {
            //清空登录信息
            useMainStore.updatedAuthToken("");
            useMainStore.updatedRefreshToken("");
            useMainStore.updatedUserInfo({});
            deleteCookie("authToken");
            deleteCookie("refreshToken");
            router.push('/login');
        } else {
            ElMessage({
                message: error.resultMsg ? error.resultMsg : "连接超时,请稍后重试",
                grouping: true,
                type: 'error',
            })
        }
    } else {
        ElMessage({
            message: "连接超时,请稍后重试",
            grouping: true,
            type: 'error',
        })
    }
    return Promise.reject(error)
})
export default uploadFileAxios

/**
* 封装get方法
* @param url
* @param params
* @returns {Promise}
*/

export function get_uploadFile(url: any, params: Object = {}) {
    return new Promise((resolve, reject) => {
        uploadFileAxios.get(url, {
            params: params
        })
            .then(response => {
                resolve(response)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
* 封装post请求
* @param url
* @param data
* @returns {Promise}
*/

export function post_uploadFile(url: any, data: Object = {}) {
    return new Promise((resolve, reject) => {
        uploadFileAxios.post(url, data)
            .then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
    })
}

/**
* 封装delete方法
* @param url
* @param params
* @returns {Promise}
*/

export function doDelete_uploadFile(url: any, params: Object = {}) {
    return new Promise((resolve, reject) => {
        uploadFileAxios.delete(url, {
            params: params
        })
            .then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/

export function patch_uploadFile(url: any, data: Object = {}) {
    return new Promise((resolve, reject) => {
        uploadFileAxios.patch(url, data)
            .then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/

export function put_uploadFile(url: any, data: Object = {}) {
    return new Promise((resolve, reject) => {
        uploadFileAxios.put(url, data)
            .then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}